<?php

declare(strict_types=1);

namespace app\model;

use think\Model;
use think\model\concern\SoftDelete;

class Order extends Model
{
    use SoftDelete;

    protected $name = 'orders';

    protected $autoWriteTimestamp = 'datetime';

    protected $json = ['amount_snapshot', 'status_history'];

    protected $append = ['status_label'];

    public const STATUS_PENDING_CONFIRM = 0;
    public const STATUS_PENDING_PAYMENT = 1;
    public const STATUS_PENDING_ASSIGN = 2;
    public const STATUS_PENDING_LOGISTICS = 3;
    public const STATUS_PENDING_SELLER_SHIP = 4;
    public const STATUS_IN_TRANSIT = 5;
    public const STATUS_COMPLETED = 6;
    public const STATUS_CANCELLED = 7;
    public const STATUS_AFTER_SALE = 8;

    public const REFUND_STATUS_NONE = 0;
    public const REFUND_STATUS_PROCESSING = 1;
    public const REFUND_STATUS_DONE = 2;

    public function items()
    {
        return $this->hasMany(OrderItem::class, 'order_id');
    }

    public function payments()
    {
        return $this->hasMany(OrderPayment::class, 'order_id');
    }

    public function refunds()
    {
        return $this->hasMany(OrderRefund::class, 'order_id');
    }

    public function shipments()
    {
        return $this->hasMany(Shipment::class, 'order_id');
    }

    public function buyer()
    {
        return $this->belongsTo(User::class, 'buyer_user_id');
    }

    public function sellerOrg()
    {
        return $this->belongsTo(Org::class, 'seller_org_id');
    }

    public function assistUser()
    {
        return $this->belongsTo(User::class, 'assist_user_id');
    }

    public static function statusMap(): array
    {
        return [
            self::STATUS_PENDING_CONFIRM => '待确认',
            self::STATUS_PENDING_PAYMENT => '待支付',
            self::STATUS_PENDING_ASSIGN => '待客服指派',
            self::STATUS_PENDING_LOGISTICS => '待物流安排',
            self::STATUS_PENDING_SELLER_SHIP => '待卖家发货',
            self::STATUS_IN_TRANSIT => '运输中',
            self::STATUS_COMPLETED => '已完成',
            self::STATUS_CANCELLED => '已取消',
            self::STATUS_AFTER_SALE => '售后处理中',
        ];
    }

    public static function labelForStatus(int $status): string
    {
        return self::statusMap()[$status] ?? '未知状态';
    }

    public function getStatusLabelAttr(): string
    {
        return self::labelForStatus((int) $this->status);
    }
}
